<?php
/**
 * FILE INTENT
 */

/**
 * Abstract class of all mail plugin init data
 * @abstract
 * @version  1.0
 * @author   Nam Nguyen <nam.ngvan@gmail.com>
 * @since    Apr 17, 2013
 */
abstract class Nuo_Nuo_Plugin_Mail_Abstract
{
	/**
	 * @access  protected
	 * @var     array
	 */
	protected $_tpl = array();

	/**
	 * @access  protected
	 * @var     array
	 */
	protected $_params = array();

	/**
	 * Result data compiled, replaced
	 * @access public
	 * @var array
	 */
	protected $_data = array();

	/**
	 * Init from data
	 *
	 * @access   public
	 * @param    array $data
	 * @return   Nuo_Plugin_Mail_Abstract
	 */
	function setTemplate($tpl)
	{
		$this -> _tpl = $tpl;
		return $this;
	}

	/**
	 * @access  public
	 * @param   any  $to
	 * @return  Nuo_Plugin_Mail_Abstract
	 */
	function setTo($to)
	{
		$this -> _params['to_address'] = $to;
		return $this;
	}

	/**
	 * @access public
	 * @param   string   $key
	 * @param   any     $value
	 * @return  Nuo_Plugin_Mail_Abstract
	 */
	public function setParam($key, $value)
	{
		$this -> _params[$key] = $value;
		return $this;
	}

	/**
	 * @access  public
	 * @param   array   $params
	 * @return  Nuo_Plugin_Mail_Abstract
	 */
	public function setParams($params)
	{
		if ($params)
		{
			foreach ($params as $key => $value)
			{
				$this -> _params[$key] = $value;
			}
		}
		return $this;

	}

	/**
	 * @access public
	 * @param   string  $key
	 * @param   any    $default
	 * @return  any
	 */
	public function getParam($key, $default = NULL)
	{
		return isset($this -> _params[$key]) ? $this -> _params[$key] : $default;
	}

	/**
	 * get all params
	 * @access public
	 * @return  array
	 */
	public function getParams()
	{
		return $this -> _params;
	}

	/**
	 * Replace place holder by params
	 * @access public
	 * @return void
	 */
	function replace()
	{

		$reg = array();

		foreach ($this->_params as $key => $value)
		{
			$reg['{' . (string)$key . '}'] = $value;
		}

		$data = $this -> _tpl;

		$data['subject'] = strtr($data['subject'], $reg);
		$data['body_text'] = strtr($data['body_text'], $reg);
		$data['body_html'] = strtr($data['body_html'], $reg);

		return $data;
	}

	function execute($tpl, $to, $params)
	{
		$this -> setTemplate($tpl) -> setTo($to) -> setParams($params);
		$this -> compile();
		return $this -> replace();
	}

	/**
	 * Compile from params to new token params if needed
	 * This method must be implement within children class
	 * No params intends here
	 * 
	 * @see mail.api.mail/compile
	 *
	 * @return void
	 */
	abstract function compile();
}
